<template>
  <div id="app" tabindex="0" ref="distributeYarnDetailRef" class="distribute-yarn-detail">
    <!-- 头部导航 -->
    <van-nav-bar title="发纱到机台" left-text="返回" left-arrow @click-left="comeBack" @click-right="scanFn">
      <template #right>
        <van-icon name="scan" size="20" />
      </template>
    </van-nav-bar>

    <!-- 需求源 -->
    <div v-show="weaving.craftId > 0" style="padding: 1vh 2vw;color: #2774b3;">
      <div style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
        <span style="margin-right: 2vw;">品号:</span><span>{{ weaving.craftName }}</span>
      </div>
      <van-radio-group v-model="weaving.machineType" direction="horizontal" @change="weaving.machineNo = SPLIT_BLANK">
        <van-radio name="1" shape="square">整经机</van-radio>
        <van-radio name="2" shape="square">织布机</van-radio>
        <van-button type="primary" size="small" @click="showActionSheetFn">
          <template #default>
            <span style="font-size: 1.2rem;font-weight: bolder">机台号:{{ weaving.machineNo }}</span>
          </template>
        </van-button>
      </van-radio-group>
      <div style="display:flex; justify-content: space-between;color: #96b327;font-size: 1.2rem;font-weight: bolder">
        <div>
          <span>总包数:{{ summary.packNum }}</span>
        </div>
        <div>
          <span>总重量:{{ summary.weight }}</span>
        </div>
      </div>
    </div>

    <better-scroll class="body-scroll" :data="packData" :totalPage="1" :pulldown="false">
      <van-cell-group v-show="packData.length !== 0">
        <van-swipe-cell v-for="(pack, index) in packData" :key="index">
          <template #default>
            <van-cell :title="'编号: ' + pack.standardNo">
              <template slot="label">
                <div class="pack-label">
                  <span>
                    <span>颜色: </span>
                    <van-field readonly :value="pack.colorName"></van-field>
                  </span>
                  <span>
                    <span>支数: </span>
                    <van-field readonly :value="pack.standard"></van-field>
                  </span>
                  <span>
                    <span>区域:</span>
                    <van-field readonly :value="pack.storeArea"></van-field>
                  </span>
                  <span>
                    <span>标重: </span>
                    <van-field readonly :value="pack.weight"></van-field>
                  </span>
                  <span>
                    <span>筒管颜色: </span>
                    <van-field readonly :value="pack.spindleColor"></van-field>
                  </span>
                  <span>
                    <span>批号: </span>
                    <van-field readonly :value="pack.lotNum"></van-field>
                  </span>
                  <span>
                    <span>区域库存: </span>
                    <van-field readonly :value="pack.areaWeight"></van-field>
                  </span>
                  <span>
                    <span>批次库存:</span>
                    <van-field readonly :value="pack.batchWeight"></van-field>
                  </span>
                </div>
              </template>
              <template>
                <span v-html="pack.id"></span>
              </template>
            </van-cell>
          </template>
          <template #right>
            <van-button square type="danger" text="删除" @click="delPackFn(index)"></van-button>
          </template>
        </van-swipe-cell>
      </van-cell-group>
      <van-empty class="custom-image" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" v-show="packData.length === 0" description="暂无数据"/>
    </better-scroll>


    <!-- 操作按钮 -->
    <div>
      <van-button v-show="packData.length > 0" block type="info" @click="confirmFn">发纱确定</van-button>
    </div>

    <!-- 盘库出库重量弹窗 -->
    <van-dialog v-model="weight.show" title="请确认发放重量" :lock-scroll="false" :show-cancel-button="true" :show-confirm-button="true" getContainer="#app" @confirm="confirmWeightFn">
      <template #default>
        <div style="padding: 3vh 4vw;">
          <van-radio-group v-model="weight.percent" direction="horizontal" @change="weight.num = (weight.all/weight.percent).toFixed(2)" >
            <van-radio name="1" shape="square">全部</van-radio>
            <van-radio name="2" shape="square">1/2</van-radio>
            <van-radio name="3" shape="square">1/3</van-radio>
            <van-radio name="4" shape="square">1/4</van-radio>
          </van-radio-group>
          <van-field class="weight-confirm" label-width="25vw" v-model="weight.num" label="重量(kg)" size="large" colon clearable placeholder="请选择或输入"></van-field>
        </div>
      </template>
    </van-dialog>

    <!-- 选择项弹窗组件 -->
    <van-action-sheet v-model="actionSheet.show" :actions="actionSheet.data" title="请选择需要的数据" cancel-text="取消" close-on-click-action get-container="#app" @cancel="actionSheet.show = false" @select="selectFilterDataFn"></van-action-sheet>
  </div>
</template>

<script>
import {SPLIT_BLANK, SPLIT_COMMA} from "@/api/enum";
import {deepCopy, openWin} from "@/utils";
import {addDistributeYarn, loadWeavingMachineData, loadYarn4Craft} from "@/views/weaving/weaving";
import {getYarnPackageFilter, yarnCheckDetail} from "@/api/yarn";

export default {
  name: "distributeYarnDetail",
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  data() {
    return {
      SPLIT_BLANK,

      /* 需求源 */
      weaving: {
        craftId: 0,
        craftName: SPLIT_BLANK,
        craftDetailId: 0,
        machineType: "1",
        machineNo: SPLIT_BLANK,
      },
      yarns: [],

      /* 数据项 */
      actionSheet: {
        show: false,
        data: []
      },
      machine: {
        lonWrap: [],    //整经机
        weaving: [],    //织布机
      },

      /* 重量确认 */
      weight: {
        show: false,
        all: 0,
        num: 0,
        percent: 0,
        pack: null,
      },

      /* 操作数据 */
      packData: [],

      /* 合计 */
      summary: {
        packNum: 0,
        weight: 0,
      }
    }
  },
  methods: {
    comeBack() {
      openWin("distribute-yarn");
    },

    /* 初始化 */
    initFn(that) {
      //加载机台
      loadWeavingMachineData({
        type: "织造-整经机"
      }, data => {
        data[0].propertyValue.split(SPLIT_COMMA).forEach(no => {
          that.machine.lonWrap.push(no)
        });
      });
      loadWeavingMachineData({
        type: "织造-剑杆机"
      }, data => {
        data[0].propertyValue.split(SPLIT_COMMA).forEach(no => {
          that.machine.weaving.push(no);
        });
      });
      loadWeavingMachineData({
        type: "织造-提花机"
      }, data => {
        data[0].propertyValue.split(SPLIT_COMMA).forEach(no => {
          that.machine.weaving.push(no);
        });
      });

      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },

    /* 显示数据项 */
    showActionSheetFn() {
      const that = this;
      that.actionSheet.data.splice(0, that.actionSheet.data.length);
      let data;
      if(that.weaving.machineType == "1") {
        data = that.machine.lonWrap;
      } else if(that.weaving.machineType == "2") {
        data = that.machine.weaving;
      } else {
        that.$toast.fail("不支持的数据项");
        return;
      }
      data.forEach(machineNo => {
        that.actionSheet.data.push({
          name: machineNo
        });
      });
      that.actionSheet.show = true;
    },
    /* 选择数据项 */
    selectFilterDataFn(action) {
      const that = this;
      that.weaving.machineNo = action.name;
      that.$toast({
        type: "success",
        message: "请继续扫纱线码",
        duration: 1500,
        onClose: () => {
          that.scanFn();
        },
      });
    },

    /* 扫码 */
    scanFn() {
      const that = this;
      const zyHmsScan = api.require("zyHmsScan");
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          let content = ret.result;
          if((content.length > 5 && content.indexOf(SPLIT_COMMA) == -1) || content.startsWith("28,")) {    //扫纱线盘库码
            //检查是否有需求源
            if(that.weaving.craftId == 0) {
              that.$toast.fail("请先扫织造盘头码");
              return;
            }
            let checkId = content;
            if(content.startsWith("28,")) {
              checkId = content.substring(3);
            }
            //检查是否已扫过
            if(that.packData.some(pack => pack.id == checkId)) {
              that.$toast.fail("已扫在列表中");
              return;
            }
            //加载盘库单
            yarnCheckDetail({checkId: checkId}, check => {
              //检查是否需要的
              if(!that.yarns.some(yarn => yarn.yarnId == check.yarnId)) {
                that.$toast.fail("所扫的纱线不是需要的")
                return;
              }
              //检查是否需要的
              if(!that.yarns.some(yarn => {
                return yarn.yarnId == check.yarnId;
              })) {
                that.$toast.fail("所扫的纱线不是需要的")
                return;
              }

              //设置纱包重
              that.weight.pack = {
                standardId: check.yarnId,
                standardNo: check.no,
                batchId: check.batchId,
                lotNum: check.lotNum,
                id: 0,
                checkId: check.id,
                colorName: check.colorName,
                standard: check.standard,
                storeArea: check.stockArea,
                weight: check.batchWeight,
                spindleColor: "无",
                areaWeight: check.areaWeight,
                batchWeight: check.batchWeight,
              };
              that.weight.all = that.weight.pack.weight;
              that.weight.show = true;
            });
          } else if(content.startsWith("{Id:'") || content.startsWith("27,")) {   //扫纱线包
            //检查是否有需求源
            if(that.weaving.craftId == 0) {
              that.$toast.fail("请先扫织造盘头码")
              return;
            }
            let packId;
            if(content.startsWith("27,")) {
              packId = content.substring(3);
            } else {
              let ids = eval(content);
              if (ids.toString().indexOf(SPLIT_COMMA) == -1) {
                that.$toast.fail("二维码异常");
                return false;
              }
              packId = ids.split(SPLIT_COMMA)[0];
            }
            //检查是否已扫过
            if(that.packData.some(pack => pack.id == packId)) {
              that.$toast.fail("已扫在列表中");
              return;
            }
            //获取后添加到列表 继续扫码
            getYarnPackageFilter(packId, pack => {
              //检查是否需要的
              if(!that.yarns.some(yarn => {
                return yarn.yarnId == pack.standardId; //向前兼容
              })) {
                that.$toast.fail("所扫的纱线不是需要的")
                return;
              }

              if(pack.status != 3) {
                that.$toast.fail("请扫出库状态的二维码");
                return;
              }

              //设置纱包重
              that.weight.pack = pack;
              that.weight.all = pack.weight;
              that.weight.percent = "1";
              that.weight.num = pack.weight;
              that.weight.show = true;
            });
          } else if(content.startsWith("98,")) {    //新版织造生产码 98,craftId,taskId,craftDetailId
            const ids = content.substr(3).split(SPLIT_COMMA);
            that.yarns.splice(0, that.yarns.length);
            loadYarn4Craft({
              craftId: ids[0]
            }, data => {
              that.weaving.craftId = data.id;
              that.weaving.craftName = data.embroideryNo;
              let toScan = false;
              if(data.loomNo && data.loomNo != SPLIT_BLANK) {
                that.weaving.machineType = "2";
                that.$nextTick(() => {
                  that.weaving.machineNo = data.loomNo;
                });
                toScan = true;
              }
              data.yarnIds.forEach(yarnId => {
                that.yarns.push({
                  yarnId: yarnId
                })
              });
              that.$toast({
                type: "success",
                message: toScan ? "扫码成功,请继续扫纱线" : "扫码成功，选择机台号",
                duration: 1500,
                onClose: () => {
                  if(toScan) {
                    that.scanFn();
                  } else {
                    that.showActionSheetFn();
                  }
                },
              });
            });
          } else {
            that.$toast.fail("请扫正确的二维码");
          }
        }
      });
    },

    /* 重量确认 */
    confirmWeightFn() {
      const that = this;
      that.weight.pack.weight = that.weight.num;
      that.packData.push(deepCopy(that.weight.pack));
      that.weight.percent = SPLIT_BLANK;
      that.weight.all = 0;
      that.$nextTick(() => {    //必须下一个视图刷新
        that.weight.num = 0;
      });
      that.calSummaryFn();
      that.$toast({
        type: "success",
        message: "扫码成功,请继续扫纱线",
        duration: 1500,
        onClose: () => {
          that.scanFn();
        },
      });
    },

    /* 删除包 */
    delPackFn(index) {
      const that = this;
      that.packData.splice(index, 1);
      that.calSummaryFn();
    },

    /* 合计 */
    calSummaryFn() {
      const that = this;
      that.summary.packNum = that.packData.length;
      that.summary.weight = that.packData.map(p => Number(p.weight)).reduce((a, b) => a + b, 0).toFixed(1);
    },

    /* 发纱确认 */
    confirmFn() {
      const that = this;
      if(that.packData.length == 0) {
        that.$toast.fail("请先扫纱线");
        return;
      }
      if(that.weaving.machineNo == SPLIT_BLANK) {
        that.$toast.fail("必须选择机台");
        return;
      }
      let param = {
        craftId: that.weaving.craftId,
        craftDetailId: that.weaving.craftDetailId,
        machineType: that.weaving.machineType,
        machineNo: that.weaving.machineNo,
        details: []
      };
      that.packData.forEach(pack => {
        param.details.push({
          yarnId: pack.standardId,
          yarnNo: pack.standardNo,
          yarnBatchId: pack.batchId,
          yarnLotNo: pack.lotNum,
          yarnPackId: pack.id,
          yarnCheckId: pack.checkId,
          weight: pack.weight,
        });
      });

      addDistributeYarn(param, res => {
        if(res.code == 0 || res.code) {
          that.$toast.fail(res.msg);
          return;
        }
        that.$toast({
          type: "success",
          message: "操作成功",
          duration: 1500,
          onClose: () => {
            that.comeBack();
          },
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.distribute-yarn-detail {
  .body-scroll {
    height: 75vh;
    overflow: hidden;
    ::v-deep .van-cell {
      .van-cell__title {
        flex: 0 0 100% !important;
      }
      .pack-label {
        display: flex;
        flex-wrap: wrap;
        padding-top: 0;
        & > span {
          display: flex;
          width: 50%;
          height: 30px;
          align-items: center;
          & > span {
            width: 100px;
          }
          .van-cell.van-field {
            padding-left: 0;
          }
        }
      }
    }
    ::v-deep .van-swipe-cell__right {
      .van-button {
        height: 100%;
      }
    }
  }
  .weight-confirm {
    margin-top: 2vh;
    ::v-deep .van-field__label {
      font-size: 1.2rem;
      color: #e6a23c;
    }
    ::v-deep .van-field__control {
      font-size: 1.2rem;
      color: #e6a23c;
      font-weight: bolder;
    }
  }
}
</style>